<?php

/*
 * Author: Quan Van Sinh
 * Email: sinhvnb@vietnambiz.com
 * Update: NghiaTruong
 * Email: nghiatruong@vietnambiz.com
 * Date: 16-3-2011
 */

class article {

    function article() {
        
    }

    function getAllArticle($limit, $status='') {
        global $db, $config;

        if ($_GET['searchArticleSubmit'] == 'Search' AND $_GET['articleActionType'] == 'searchArticle') {
            $keyword = $_GET['searchKeyword'];
            $dateFrom = filter($_GET['dateFrom']);
            $dateTo = filter($_GET['dateTo']);
            $catId = intval($_GET['categoryId']);

            if (isset($_SESSION['articlePageEdit'])) {
                $config['page'] = $_SESSION['articlePageEdit'];
            }

            if (intval($catId) > 0) {
                $catTree = $this->get_cat_tree($catId);
                foreach ($catTree as $k => $rs) {
                    $cat_id_string .= $rs['id'] . ',';
                }
                if ($cat_id_string != '') {
                    $cat_id_string = substr($cat_id_string, 0, -1);
                } else {
                    $cat_id_string = $catId;
                }
            }

            $condition = "";
            if ($keyword != '') {
                $condition = " WHERE (a.title LIKE '%" . filter($keyword) . "%' OR a.description LIKE '%" . filter($keyword) . "%') ";
                if ($dateFrom != '' AND $dateTo != '') {
                    $condition .= " AND (a.create_date >='$dateFrom 00:00:00' AND a.create_date <='$dateTo 23:59:59') ";
                }
                if (intval($catId) > 0) {
                    $condition .= " AND (a.cat_id=" . intval($catId) . " OR a.cat_id IN ($cat_id_string) ) ";
                }
            } else {
                if ($dateFrom != '' AND $dateTo != '') {
                    $condition .= " WHERE (a.create_date >='$dateFrom 00:00:00' AND a.create_date <='$dateTo 23:59:59') ";
                    if ($catId != '') {
                        $condition .= " AND (a.cat_id=" . intval($catId) . " OR a.cat_id IN ($cat_id_string) ) ";
                    }
                } else {
                    if (intval($catId) > 0) {
                        $condition .= " WHERE (a.cat_id=" . intval($catId) . " OR a.cat_id IN ($cat_id_string) ) ";
                    }
                }
            }

            if (isset($_SESSION['articleStatusFilter']) AND $_SESSION['articleStatusFilter'] != '') {
                if ($condition != '') {
                    $status = " AND a.status='" . filter($_SESSION['articleStatusFilter']) . "' ";
                } else {
                    $status = " WHERE a.status='" . filter($_SESSION['articleStatusFilter']) . "' ";
                }

                $condition .= $status;
            }

            $sqlTotalRows = "SELECT count(*) as total FROM article a" . $condition;
            $totalRows = $db->query_first($sqlTotalRows);

            $totalPages = ceil($totalRows['total'] / $config ['total_article_on_admin']);
            $start = (($config ['page'] * $config ['total_article_on_admin']) - $config ['total_article_on_admin']);
            $sql = "SELECT a.*,c.name as category_name FROM article a LEFT JOIN article_category c ON a.cat_id=c.id " . $condition . " ORDER BY create_date DESC LIMIT $start,$limit";
            $rsAllArticle = $db->query($sql);
        } else {
            if (isset($_SESSION['articleStatusFilter']) AND $_SESSION['articleStatusFilter'] != '') {
                $status = " WHERE a.status='" . filter($_SESSION['articleStatusFilter']) . "' ";
            }

            $sqlTotalRows = "SELECT count(*) as total FROM article a" . $condition;
            $totalRows = $db->query_first($sqlTotalRows);

            $totalPages = ceil($totalRows['total'] / $config ['total_article_on_admin']);
            $start = (($config ['page'] * $config ['total_article_on_admin']) - $config ['total_article_on_admin']);
            $sql = "SELECT a.*,c.name as category_name FROM article a LEFT JOIN article_category c ON a.cat_id=c.id " . $status . " ORDER BY create_date DESC LIMIT $start,$limit";
            $rsAllArticle = $db->query($sql);
        }
        return Array("rs" => $rsAllArticle, "totalRows" => $totalRows['total']);
    }

    function checkArticleExist($articlename) {
        global $db;
        $sql = "SELECT * FROM article WHERE articlename='" . mysql_escape_string($articlename) . "'";
        $rsArticle = $db->query_first($sql);
        if ($rsArticle['articlename'] != '$articlename') {
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function articleAction() {
        global $config;
        if (isset($_REQUEST['articleActionType'])) {
            $actionType = $_REQUEST['articleActionType'];
            switch ($actionType) {
                case 'addArticle':
                    $this->addArticle();
                    break;
                case 'viewAddArticle':
                    break;
                case 'editArticle':
                    break;
                case 'updateArticle':
                    if (isset($_POST['id'])) {
                        $this->updateArticle($_POST['id']);
                    } else {
                        $this->getAllArticle($config ['total_article_on_admin']);
                    }
                    break;
                case 'updateFrontPageDate':
                    if (isset($_POST['id'])) {
                        $this->updateArticleFrontPageDate($_POST['id']);
                    } else {
                        $this->getAllArticle($config ['total_article_on_admin']);
                    }
                    break;
                case 'deleteArticle':
                    if (isset($_POST['id'])) {
                        $this->deleteArticle($_POST['id']);
                    } else {
                        $this->getAllArticle($config ['total_article_on_admin']);
                    }
                    break;
                case 'actionMultil':
                    if (isset($_POST['multiArticleId'])) {
                        $this->actionMultil();
                    } else {
                        $_SESSION['rsMessages'] = '<span class="error">Please select the articles to perform action!</span>';
                        $this->getAllArticle($config ['total_article_on_admin']);
                    }
                    break;
                default:
                    $this->getAllArticle($config ['total_article_on_admin']);
            }
        }
    }

    function actionMultil() {
        global $db, $config;
        $ids = $_POST['multiArticleId'];
        switch ($_POST['action']) {
            case 'delete':
                for ($i = 0; $i < count($ids); $i++) {
                    $this->deleteArticle(intval($ids[$i]), 'multi');
                }
                $_SESSION['rsMessages'] = '<span class="success">Delete the articles successfull!</span>';
                break;
            case 'yes':
                for ($i = 0; $i < count($ids); $i++) {
                    $db->query("UPDATE article set status='yes' WHERE id=" . intval($ids[$i]));
                }
                $_SESSION['rsMessages'] = '<span class="success">Change status to yes successfull!</span>';
                break;
            case 'pending':
                for ($i = 0; $i < count($ids); $i++) {
                    $db->query("UPDATE article set status='pending' WHERE id=" . intval($ids[$i]));
                }
                $_SESSION['rsMessages'] = '<span class="success">Change status to pending successfull!</span>';
                break;
            case 'no':
                for ($i = 0; $i < count($ids); $i++) {
                    $db->query("UPDATE article set status='no' WHERE id=" . intval($ids[$i]));
                }
                $_SESSION['rsMessages'] = '<span class="success">Change status to no successfull!</span>';
                break;
            default:
                $this->getAllArticle($config ['total_house_on_article_admin']);
        }
    }

    function addArticle() {
        global $db, $config;
        $upload_dir = $config ['upload_dir'] . '/article_attachs/' . date("Y") . '/' . date("m");
        $upload_dir_attach_insert = '/article_attachs/' . date("Y") . '/' . date("m");
        $title = mysql_escape_string($_POST['title']);
        $link = CleanFileName(filter($_POST['title'])) . '-' . rand(0, 999);
        $cat_id = intval($_POST['categoryId']);
        $image = filter($_POST['image']);
        $short_description = mysql_escape_string($_POST['short_description']);
        $description = mysql_escape_string($_POST['description']);
        $status = filter($_POST['status']);
        $comment = filter($_POST['comment']);
        $show_comment = filter($_POST['show_comment']);
        $front_page = filter($_POST['front_page']);
        $create_date = $_POST['createDate'];
        $tags = $_POST['keyword'];
        $attachs = $_FILES['attachs'];
        $now = time();

        //insert data to article table
        if ($create_date == '') {
            $create_date = date('Y-m-d H:i:s');
        }

        $addArticleSql = "INSERT INTO article (cat_id,title,link,short_description,description,image,user_id,create_date,front_page,front_page_date,status,comment,show_comment)
                            VALUES
                          ($cat_id,'$title','$link','$short_description','$description','$image'," . $_SESSION['userid'] . ",'$create_date','$front_page','$create_date','$status','$comment','$show_comment')";
        $db->query($addArticleSql);
        $articleId = $db->mysql_insert_id();
                
        addEditRelateBox($articleId, 'article');
        

        //insert data to tags
        for ($i = 0; $i < count($tags); $i++) {
            if ($tags[$i] != '') {
                $tempTags = $this->checkTagExist($tags[$i]);
                if ($tempTags == 'donthave') {//chua ton` tai tag nay nen insert vao database
                    $tags_link = CleanFileName(filter($tags[$i]));
                    $db->query("INSERT INTO tags (tags, tags_link) VALUES ('$tags[$i]', '$tags_link')");
                    $db->query("INSERT INTO article_tags (article_id,tag_id) VALUES ($articleId," . $db->mysql_insert_id() . ")");
                } else {//ton tai rui nen lay id (chinh la $tempTags)
                    $db->query("INSERT INTO article_tags (article_id,tag_id) VALUES ($articleId,$tempTags)");
                }
            }
        }

        //insert attachs
        if (count($attachs['name']) > 0) {
            for ($i = 0; $i < count($attachs['name']); $i++) {
                $arrAttachsNameExplode = explode('.', $attachs["name"][$i]);
                $attachsExtention = $arrAttachsNameExplode[(count($arrAttachsNameExplode) - 1)];
                $realFileName = $attachs["name"][$i];
                $filename = $now . '-' . rand(0, 999999) . '.' . strtolower($attachsExtention);
                $filesize = $attachs["size"][$i];
                if (!file_exists($upload_dir)) {
                    if (!mkdir($upload_dir, 0777, true)) {
                        $_SESSION['rsMessages'] .= "<span class='error'>Can not create directory, please check permission.</span><br/>";
                    }
                }
                if (move_uploaded_file($attachs["tmp_name"][$i], $upload_dir . "/" . $filename)) {
                    $db->query("INSERT INTO article_attach (article_id,real_filename,filename,filesize,create_date) VALUES ($articleId,'$realFileName','$upload_dir_attach_insert/$filename','$filesize','$create_date')");
                }
            }
        }

        $_SESSION['rsMessages'] = "<span class='success'>Add new article successfull!</span>";
    }

    function checkTagExist($tag) {
        global $db;
        $rs = $db->query_first("SELECT id FROM tags WHERE tags='$tag'");
        if ($rs) {
            return $rs['id'];
        } else {
            return 'donthave';
        }
    }

    function checkArticleTagExist($article_id, $tag_id) {
        global $db;
        $rs = $db->query_first("SELECT id FROM article_tags WHERE article_id=$article_id AND tag_id=$tag_id");
        if ($rs) {
            return $rs['id'];
        } else {
            return 'donthave';
        }
    }

    function editArticle($id) {
        global $db;

        $sql = "SELECT * FROM article WHERE id = " . intval($id);
        $rsArticle = $db->query_first($sql);

        $sql = "SELECT t.* FROM article_tags at LEFT JOIN tags t ON at.tag_id=t.id WHERE at.article_id=" . intval($id);
        $rsTags = $db->query($sql);

        $sql = "SELECT * FROM box_relation WHERE art_cat_id = " . intval($id) . " AND relate_for='article'";
        $rsRelateBox = $db->query_first($sql);
        if (!empty($rsRelateBox['value']) && $rsRelateBox['relate_for'] == 'article') {
            $rs = $db->query("SELECT id,title FROM article WHERE id IN (" . $rsRelateBox['value'] . ")");
            $html = '';
            while ($row = $db->fetch_array($rs)) {
                $html .= '<option value="' . $row['id'] . '" title="' . $row['title'] . '">' . $row['title'] . '</option>';
            }
            $returnData['rbValue'] = $html;
            $rsRelateBox['articleValue'] = $html;
        }
        $_SESSION['url_before_edit'] = $_SERVER['HTTP_REFERER'];
        return array('rsArticle' => $rsArticle, 'rsTags' => $rsTags, 'rsRelateBox' => $rsRelateBox);
    }

    function updateArticle($id) {
        global $db, $config;
        $upload_dir = $config ['upload_dir'] . '/article_attachs/' . date("Y") . '/' . date("m");
        $upload_dir_attach_insert = '/article_attachs/' . date("Y") . '/' . date("m");
        $id = intval($id);
        $title = mysql_escape_string($_POST['title']);
        //$link = CleanFileName(filter($_POST['title'])).'-'.rand(0,999);
        $cat_id = intval($_POST['categoryId']);
        $image = filter($_POST['image']);
        $short_description = mysql_escape_string($_POST['short_description']);
        $description = mysql_escape_string($_POST['description']);
        $status = filter($_POST['status']);
        $comment = filter($_POST['comment']);
        $show_comment = filter($_POST['show_comment']);
        $front_page = filter($_POST['front_page']);
        $tags = $_POST['keyword'];
        $createDate = $_POST['createDate'];
        $removedTags = explode(',', $_POST['removedTags']);
        $removeAttachs = $_POST['removeAttachs'];
        $attachs = $_FILES['attachs'];
        $now = time();

        $rsCheckFrontPage = $db->query_first("SELECT front_page FROM article WHERE id=" . intval($id));
        if ($rsCheckFrontPage['front_page'] == 'no' && $front_page == 'yes' && $createDate != '') {
            $front_page_date = date('Y-m-d H:i:s');
            $updateArticleSql = "UPDATE article SET cat_id=$cat_id,
                        title='$title', image='$image', short_description='$short_description', description='$description', front_page='$front_page', create_date='$createDate', front_page_date='$front_page_date', status='$status', comment='$comment',show_comment='$show_comment'
                        WHERE id = " . $id;
        } elseif ($createDate != '') {
            $updateArticleSql = "UPDATE article SET cat_id=$cat_id,
                        title='$title', image='$image', short_description='$short_description', description='$description', front_page='$front_page', create_date='$createDate', status='$status', comment='$comment',show_comment='$show_comment'
                        WHERE id = " . $id;
        } else {
            $updateArticleSql = "UPDATE article SET cat_id=$cat_id,
                        title='$title', image='$image', short_description='$short_description', description='$description', front_page='$front_page', status='$status', comment='$comment',show_comment='$show_comment'
                        WHERE id = " . $id;
        }

        addEditRelateBox($id, 'article');

        if ($id != 0) {
            $db->query($updateArticleSql); //update article table
                       
            //delete tag had been removed
            for ($i = 0; $i < count($removedTags); $i++) {
                if ($removedTags[$i] != '') {
                    $rsRemoveTagId = $db->query_first("SELECT id FROM tags WHERE tags='" . $removedTags[$i] . "'");
                    if ($rsRemoveTagId['id'] != 0) {
                        $db->query("DELETE FROM article_tags WHERE 1 AND article_id=$id AND tag_id = " . $rsRemoveTagId['id']);
                    }
                }
            }
            //insert data to tags table
            for ($i = 0; $i < count($tags); $i++) {
                if ($tags[$i] != '') {
                    $tempTags = $this->checkTagExist($tags[$i]);
                    if ($tempTags == 'donthave') {//chua ton` tai tag nay nen insert vao database
                        $tags_link = CleanFileName(filter($tags[$i]));
                        $db->query("INSERT INTO tags (tags, tags_link) VALUES ('$tags[$i]', '$tags_link')");
                        $db->query("INSERT INTO article_tags (article_id,tag_id) VALUES ($id," . $db->mysql_insert_id() . ")");
                    } else {//ton tai rui nen lay id (chinh la $tempTags)
                        if ($this->checkArticleTagExist($id, $tempTags) == 'donthave') {
                            $db->query("INSERT INTO article_tags (article_id,tag_id) VALUES ($id,$tempTags)");
                        }
                    }
                }
            }

            //remove attachs file
            if (count($removeAttachs) > 0) {
                for ($i = 0; $i < count($removeAttachs); $i++) {
                    $deleteAttachFileSql = "SELECT filename FROM article_attach WHERE id = " . intval($removeAttachs[$i]);
                    $rsDeleteAttach = $db->query_first($deleteAttachFileSql);
                    $filenameDelete = $config ['upload_dir'] . $rsDeleteAttach['filename'];
                    if (unlink($filenameDelete)) {
                        $db->query("DELETE FROM article_attach WHERE id = " . intval($removeAttachs[$i]));
                    }
                }
            }

            //insert attachs

            for ($i = 0; $i < count($attachs['name']); $i++) {
                $arrAttachsNameExplode = explode('.', $attachs["name"][$i]);
                $attachsExtention = $arrAttachsNameExplode[(count($arrAttachsNameExplode) - 1)];
                $realFileName = $attachs["name"][$i];
                $filename = $now . '-' . rand(0, 999999) . '.' . strtolower($attachsExtention);
                $filesize = $attachs["size"][$i];
                if (!file_exists($upload_dir)) {
                    if (!mkdir($upload_dir, 0777, true)) {
                        $_SESSION['rsMessages'] .= "<span class='error'>Can not create directory, please check permission.</span><br/>";
                    }
                }
                if (move_uploaded_file($attachs["tmp_name"][$i], $upload_dir . "/" . $filename)) {
                    $create_date = date('Y-m-d H:i:s');
                    $db->query("INSERT INTO article_attach (article_id,real_filename,filename,filesize,create_date) VALUES ($id,'$realFileName','$upload_dir_attach_insert/$filename','$filesize','$create_date')");
                }
            }
        }
        header("Location: " . $_SESSION['url_before_edit']);
    }

    function getArticleAttachs($id) {
        global $db;
        $sql = "SELECT * FROM article_attach WHERE article_id = " . intval($id);
        $rs = $db->query($sql);
        return $rs;
    }

    function updateArticleFrontPageDate($id) {
        global $db;
        $rsCheck = $db->query_first("SELECT front_page FROM article WHERE id=" . intval($id));
        if ($rsCheck['front_page'] == 'yes') {
            $db->query_first("UPDATE article SET front_page='no' WHERE id=" . intval($id));
            echo 'no';
            die;
        } elseif ($rsCheck['front_page'] == 'no') {
            $create_date = date('Y-m-d H:i:s');
            $db->query_first("UPDATE article SET front_page='yes', front_page_date='$create_date', status='yes' WHERE id=" . intval($id));
            echo 'yes';
            die;
        } else {
            echo 'hack';
            die;
        }
    }

    function deleteArticle($id, $multi='') {
        global $db;
        global $config;
        if ($multi == '') {
            $deleteArticleSql = "DELETE FROM article WHERE id = " . intval($id);
            $db->query($deleteArticleSql);

            $deleteArticleTagsSql = "DELETE FROM article_tags WHERE article_id = " . intval($id);
            $db->query($deleteArticleTagsSql);

            $_SESSION['rsMessages'] = "<span class='success'>Delete article successfull!</span>";
            die;
        } else {
            $deleteArticleSql = "DELETE FROM article WHERE id = " . intval($id);
            $db->query($deleteArticleSql);
            $deleteArticleTagsSql = "DELETE FROM article_tags WHERE article_id = " . intval($id);
            $db->query($deleteArticleTagsSql);
            $_SESSION['rsMessages'] = "<span class='success'>Delete article successfull!</span>";
        }
    }

    function get_cat_tree($parent_id = 0, $space = ' ', $trees = NULL) {
        global $db;
        if (!$trees)
            $trees = array();
        $sql = $db->query("SELECT * FROM article_category WHERE  parent_id = " . intval($parent_id));
        while ($rs = $db->fetch_array($sql)) {
            if ($parent_id == 0) {
                $trees[] = array('id' => $rs['id'], 'name' => $rs['name']);
            } else {
                $trees[] = array('id' => $rs['id'], 'name' => $space . $rs['name']);
            }

            $trees = $this->get_cat_tree($rs['id'], $space . '----', $trees);
        }
        return $trees;
    }

}

?>
